/*
 * P2pView.java
 */
package gui;

import dataTypes.DownloadFile;
import java.awt.event.KeyEvent;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.Task;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import gui.P2pApp;
import gui.dataTypes.DownloadTask;
import gui.dataTypes.SharedFile;
import java.awt.Button;
import java.awt.Component;
import java.awt.event.ComponentAdapter;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.swing.JTable;
import javax.swing.event.MenuDragMouseEvent;

class MyListner extends KeyAdapter {

    private P2pView view;

    @Override
    public void keyPressed(KeyEvent e) {
        view.refreshButtonsStates();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        view.refreshButtonsStates();
    }

    void setView(P2pView view) {
        this.view = view;
    }
};

/**
 * The application's main frame.
 */
public class P2pView extends FrameView {

    private P2pApp manager;
    private TreeMap<Integer, Component> panels;

    public P2pView(SingleFrameApplication app) {
        super(app);
        manager = (P2pApp) app;
        panels = new TreeMap<Integer, Component>();
        System.out.println("GUI: P2pView init");
        initComponents();
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });

        MyListner listner = new MyListner();
        listner.setView(this);
        downloadsTable.addKeyListener(listner);
    }

    public int getSelectedDownloadRowId() {
        JTable selected;
        int id;
        if (viewDownloads.isShowing()) {
            selected = downloadsTable;
        } else {
            return -1;
        }
        if (selected.getRowCount() == 0) {
            return -2;
        } else {
            id = selected.getSelectedRow();
            return id >= selected.getRowCount() ? -1 : id;
        }
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = P2pApp.getApplication().getMainFrame();
            aboutBox =
                    new P2pAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }

        P2pApp.getApplication().show(aboutBox);
    }

    @Action
    public void showSearchPanel() {
        int i = manager.getAndIncSearchCount();
        SearchPanel panel = new SearchPanel("Search #" + i, i);
        viewPanels.add(panel);
        viewPanels.setSelectedIndex(viewPanels.getTabCount() - 1);
        panels.put(new Integer(i), panel);
    }

    @Action
    public void requestShowPropertiesWindow() {
        manager.displayPropertiesWinUserReq();
    }

    protected void showPreferencesWindow(int maxActiveConnections, int connectionsPerDownload) {
        if (propertiesWin == null) {
            JFrame mainFrame = P2pApp.getApplication().getMainFrame();
            propertiesWin =
                    new PropertiesWindow();
            propertiesWin.setTitle("Properties");
            propertiesWin.setLocationRelativeTo(mainFrame);
        }

        P2pApp.getApplication().show(propertiesWin);
        propertiesWin.setCurrentPreferences(maxActiveConnections, connectionsPerDownload);
    }

    protected void showActiveHostsPanel() {
        viewPanels.add(new ActiveHosts(), 2);
        viewPanels.setSelectedIndex(2);
    }

    protected void closeActiveHostsPanel() {
        viewPanels.remove(2);
        activeHostsButton.setEnabled(true);
    }

    protected void remSearchPanel(int id) {
        viewPanels.remove(panels.get(new Integer(id)));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        viewPanels = new javax.swing.JTabbedPane();
        viewDownloads = new javax.swing.JPanel();
        stopDownloadButton = new javax.swing.JButton();
        startDownloadButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        moveTopButton = new javax.swing.JButton();
        moveUpButton = new javax.swing.JButton();
        moveDownButton = new javax.swing.JButton();
        moveBottomButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        downloadsTable = new javax.swing.JTable();
        jSeparator2 = new javax.swing.JSeparator();
        deleteDownloadButton = new javax.swing.JButton();
        viewShared = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        sharedFilesTable = new javax.swing.JTable();
        addSharedButton = new javax.swing.JButton();
        removesharedButton = new javax.swing.JButton();
        activeHostsButton = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        propertiesMenu = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(gui.P2pApp.class).getContext().getActionMap(P2pView.class, this);
        jButton1.setAction(actionMap.get("showSearchPanel")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gui.P2pApp.class).getContext().getResourceMap(P2pView.class);
        jButton1.setIcon(resourceMap.getIcon("searchButton.icon")); // NOI18N
        jButton1.setText(resourceMap.getString("searchButton.text")); // NOI18N
        jButton1.setToolTipText(resourceMap.getString("searchButton.toolTipText")); // NOI18N
        jButton1.setActionCommand(resourceMap.getString("searchButton.actionCommand")); // NOI18N
        jButton1.setBorderPainted(false);
        jButton1.setContentAreaFilled(false);
        jButton1.setDefaultCapable(false);
        jButton1.setFocusPainted(false);
        jButton1.setName("searchButton"); // NOI18N
        jButton1.setRolloverEnabled(false);

        jButton2.setAction(actionMap.get("quitRequest")); // NOI18N
        jButton2.setIcon(resourceMap.getIcon("exitButton.icon")); // NOI18N
        jButton2.setText(resourceMap.getString("exitButton.text")); // NOI18N
        jButton2.setToolTipText(resourceMap.getString("exitButton.toolTipText")); // NOI18N
        jButton2.setBorderPainted(false);
        jButton2.setContentAreaFilled(false);
        jButton2.setDefaultCapable(false);
        jButton2.setFocusPainted(false);
        jButton2.setName("exitButton"); // NOI18N
        jButton2.setRolloverEnabled(false);

        viewPanels.setName("viewPanels"); // NOI18N

        viewDownloads.setName("viewDownloads"); // NOI18N

        stopDownloadButton.setIcon(resourceMap.getIcon("stopButton.icon")); // NOI18N
        stopDownloadButton.setToolTipText(resourceMap.getString("stopButton.toolTipText")); // NOI18N
        stopDownloadButton.setBorderPainted(false);
        stopDownloadButton.setContentAreaFilled(false);
        stopDownloadButton.setDefaultCapable(false);
        stopDownloadButton.setEnabled(false);
        stopDownloadButton.setFocusPainted(false);
        stopDownloadButton.setName("stopButton"); // NOI18N
        stopDownloadButton.setRolloverEnabled(false);
        stopDownloadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopDownloadButtonActionPerformed(evt);
            }
        });

        startDownloadButton.setIcon(resourceMap.getIcon("startButton.icon")); // NOI18N
        startDownloadButton.setToolTipText(resourceMap.getString("startButton.toolTipText")); // NOI18N
        startDownloadButton.setBorderPainted(false);
        startDownloadButton.setContentAreaFilled(false);
        startDownloadButton.setDefaultCapable(false);
        startDownloadButton.setEnabled(false);
        startDownloadButton.setFocusPainted(false);
        startDownloadButton.setName("startButton"); // NOI18N
        startDownloadButton.setRolloverEnabled(false);
        startDownloadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startDownloadButtonActionPerformed(evt);
            }
        });

        jSeparator1.setName("jSeparator1"); // NOI18N

        moveTopButton.setIcon(resourceMap.getIcon("moveTopButton.icon")); // NOI18N
        moveTopButton.setToolTipText(resourceMap.getString("moveTopButton.toolTipText")); // NOI18N
        moveTopButton.setBorderPainted(false);
        moveTopButton.setContentAreaFilled(false);
        moveTopButton.setDefaultCapable(false);
        moveTopButton.setEnabled(false);
        moveTopButton.setFocusPainted(false);
        moveTopButton.setName("moveTopButton"); // NOI18N
        moveTopButton.setRolloverEnabled(false);
        moveTopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveTopButtonActionPerformed(evt);
            }
        });

        moveUpButton.setIcon(resourceMap.getIcon("moveUpButton.icon")); // NOI18N
        moveUpButton.setToolTipText(resourceMap.getString("moveUpButton.toolTipText")); // NOI18N
        moveUpButton.setBorderPainted(false);
        moveUpButton.setContentAreaFilled(false);
        moveUpButton.setDefaultCapable(false);
        moveUpButton.setEnabled(false);
        moveUpButton.setFocusPainted(false);
        moveUpButton.setName("moveUpButton"); // NOI18N
        moveUpButton.setRolloverEnabled(false);
        moveUpButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveUpButtonActionPerformed(evt);
            }
        });

        moveDownButton.setIcon(resourceMap.getIcon("moveDownButton.icon")); // NOI18N
        moveDownButton.setToolTipText(resourceMap.getString("moveDownButton.toolTipText")); // NOI18N
        moveDownButton.setBorderPainted(false);
        moveDownButton.setContentAreaFilled(false);
        moveDownButton.setDefaultCapable(false);
        moveDownButton.setEnabled(false);
        moveDownButton.setFocusPainted(false);
        moveDownButton.setName("moveDownButton"); // NOI18N
        moveDownButton.setRolloverEnabled(false);
        moveDownButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveDownButtonActionPerformed(evt);
            }
        });

        moveBottomButton.setIcon(resourceMap.getIcon("moveBottomButton.icon")); // NOI18N
        moveBottomButton.setToolTipText(resourceMap.getString("moveBottomButton.toolTipText")); // NOI18N
        moveBottomButton.setBorderPainted(false);
        moveBottomButton.setContentAreaFilled(false);
        moveBottomButton.setDefaultCapable(false);
        moveBottomButton.setEnabled(false);
        moveBottomButton.setFocusPainted(false);
        moveBottomButton.setName("moveBottomButton"); // NOI18N
        moveBottomButton.setRolloverEnabled(false);
        moveBottomButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveBottomButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        downloadsTable.setModel(manager.getDownloadModel());
        downloadsTable.setName("downloadsTable"); // NOI18N
        downloadsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        downloadsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                downloadsTableRowSelected(evt);
            }
        });
        jScrollPane1.setViewportView(downloadsTable);
        downloadsTable.getColumnModel().getColumn(1).setPreferredWidth(50);
        downloadsTable.getAccessibleContext().setAccessibleName(resourceMap.getString("downloadsTable.AccessibleContext.accessibleName")); // NOI18N

        jSeparator2.setName("jSeparator2"); // NOI18N

        deleteDownloadButton.setIcon(resourceMap.getIcon("deleteDownloadButton.icon")); // NOI18N
        deleteDownloadButton.setToolTipText(resourceMap.getString("deleteDownloadButton.toolTipText")); // NOI18N
        deleteDownloadButton.setBorderPainted(false);
        deleteDownloadButton.setContentAreaFilled(false);
        deleteDownloadButton.setDefaultCapable(false);
        deleteDownloadButton.setEnabled(false);
        deleteDownloadButton.setFocusPainted(false);
        deleteDownloadButton.setName("deleteDownloadButton"); // NOI18N
        deleteDownloadButton.setRolloverEnabled(false);
        deleteDownloadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteDownloadButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout viewDownloadsLayout = new javax.swing.GroupLayout(viewDownloads);
        viewDownloads.setLayout(viewDownloadsLayout);
        viewDownloadsLayout.setHorizontalGroup(
            viewDownloadsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, viewDownloadsLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 825, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(viewDownloadsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(viewDownloadsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(viewDownloadsLayout.createSequentialGroup()
                            .addGap(12, 12, 12)
                            .addComponent(jSeparator1)
                            .addGap(12, 12, 12))
                        .addComponent(moveTopButton)
                        .addComponent(moveUpButton)
                        .addComponent(moveDownButton)
                        .addComponent(moveBottomButton)
                        .addComponent(stopDownloadButton, 0, 0, Short.MAX_VALUE)
                        .addComponent(startDownloadButton, javax.swing.GroupLayout.PREFERRED_SIZE, 48, Short.MAX_VALUE))
                    .addGroup(viewDownloadsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, viewDownloadsLayout.createSequentialGroup()
                            .addComponent(deleteDownloadButton, 0, 0, Short.MAX_VALUE)
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, viewDownloadsLayout.createSequentialGroup()
                            .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE)
                            .addGap(12, 12, 12)))))
        );
        viewDownloadsLayout.setVerticalGroup(
            viewDownloadsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(viewDownloadsLayout.createSequentialGroup()
                .addGroup(viewDownloadsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(viewDownloadsLayout.createSequentialGroup()
                        .addComponent(startDownloadButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stopDownloadButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(moveTopButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(moveUpButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(moveDownButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(moveBottomButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteDownloadButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE))
                .addContainerGap())
        );

        viewPanels.addTab(resourceMap.getString("viewDownloads.TabConstraints.tabTitle"), viewDownloads); // NOI18N

        viewShared.setName("viewShared"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        sharedFilesTable.setModel(manager.getSharedModel());
        sharedFilesTable.setName("sharedFilesTable"); // NOI18N
        sharedFilesTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        sharedFilesTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                sharedFilesTableMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(sharedFilesTable);
        sharedFilesTable.getAccessibleContext().setAccessibleName(resourceMap.getString("sharedFilesTable.AccessibleContext.accessibleName")); // NOI18N

        addSharedButton.setIcon(resourceMap.getIcon("addSharedButton.icon")); // NOI18N
        addSharedButton.setToolTipText(resourceMap.getString("addSharedButton.toolTipText")); // NOI18N
        addSharedButton.setBorderPainted(false);
        addSharedButton.setContentAreaFilled(false);
        addSharedButton.setDefaultCapable(false);
        addSharedButton.setFocusPainted(false);
        addSharedButton.setName("addSharedButton"); // NOI18N
        addSharedButton.setRolloverEnabled(false);
        addSharedButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addSharedClicked(evt);
            }
        });

        removesharedButton.setIcon(resourceMap.getIcon("removesharedButton.icon")); // NOI18N
        removesharedButton.setToolTipText(resourceMap.getString("removesharedButton.toolTipText")); // NOI18N
        removesharedButton.setBorderPainted(false);
        removesharedButton.setContentAreaFilled(false);
        removesharedButton.setDefaultCapable(false);
        removesharedButton.setEnabled(false);
        removesharedButton.setFocusPainted(false);
        removesharedButton.setName("removesharedButton"); // NOI18N
        removesharedButton.setRolloverEnabled(false);
        removesharedButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                remSharedClicked(evt);
            }
        });

        javax.swing.GroupLayout viewSharedLayout = new javax.swing.GroupLayout(viewShared);
        viewShared.setLayout(viewSharedLayout);
        viewSharedLayout.setHorizontalGroup(
            viewSharedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, viewSharedLayout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 825, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(viewSharedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(addSharedButton)
                    .addComponent(removesharedButton)))
        );
        viewSharedLayout.setVerticalGroup(
            viewSharedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(viewSharedLayout.createSequentialGroup()
                .addGroup(viewSharedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(viewSharedLayout.createSequentialGroup()
                        .addComponent(addSharedButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removesharedButton))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE))
                .addContainerGap())
        );

        viewPanels.addTab(resourceMap.getString("viewShared.TabConstraints.tabTitle"), viewShared); // NOI18N

        activeHostsButton.setAction(actionMap.get("showActiveHostsReq")); // NOI18N
        activeHostsButton.setIcon(resourceMap.getIcon("activeHostsButton.icon")); // NOI18N
        activeHostsButton.setText(resourceMap.getString("activeHostsButton.text")); // NOI18N
        activeHostsButton.setToolTipText(resourceMap.getString("activeHostsButton.toolTipText")); // NOI18N
        activeHostsButton.setBorderPainted(false);
        activeHostsButton.setContentAreaFilled(false);
        activeHostsButton.setDefaultCapable(false);
        activeHostsButton.setFocusPainted(false);
        activeHostsButton.setName("activeHostsButton"); // NOI18N
        activeHostsButton.setRolloverEnabled(false);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(activeHostsButton)
                .addContainerGap(692, Short.MAX_VALUE))
            .addComponent(viewPanels, javax.swing.GroupLayout.DEFAULT_SIZE, 902, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2)
                    .addComponent(jButton1)
                    .addComponent(activeHostsButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(viewPanels, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        exitMenuItem.setAction(actionMap.get("quitRequest")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setToolTipText(resourceMap.getString("exitMenuItem.toolTipText")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setText(resourceMap.getString("editMenu.text")); // NOI18N
        editMenu.setName("editMenu"); // NOI18N

        propertiesMenu.setAction(actionMap.get("requestShowPropertiesWindow")); // NOI18N
        propertiesMenu.setText(resourceMap.getString("propertiesMenu.text")); // NOI18N
        propertiesMenu.setName("propertiesMenu"); // NOI18N
        editMenu.add(propertiesMenu);

        menuBar.add(editMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 902, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 718, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void addSharedClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addSharedClicked
        // TODO add your handling code here:
        manager.displayAddSharedWindow();
    }//GEN-LAST:event_addSharedClicked

    private void remSharedClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_remSharedClicked
        // TODO add your handling code here:
        int id = sharedFilesTable.getSelectedRow();
        if (id != -1) {
            manager.outDelShared(getSharedFilename(id), getSharedPath(id));
        }

    }//GEN-LAST:event_remSharedClicked

    protected void refreshButtonsStates() {
        downloadsTableRowSelected(null);
    }

    private void downloadsTableRowSelected(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_downloadsTableRowSelected
        // TODO add your handling code here:
        int i = getSelectedDownloadRowId();
        
        if (i >= 0) {
            boolean top = false, bottom = false, active = false;
            /* check position - if on top, then disable move up buttons
             *  if on bottom, then disable move down buttons
             */
            Object obj = downloadsTable.getValueAt(i, 2);
            DownloadFile.DownloadStateType state = null;
            if (obj instanceof DownloadFile.DownloadStateType) {
                state = (DownloadFile.DownloadStateType) obj;
                switch (state) {
                    case ACTIVE:
                    //it must be empty and without break statement
                    case WAITING_FOR_HOSTS:
                    case WAITING:
                        stopDownloadButton.setEnabled(true);
                        startDownloadButton.setEnabled(false);
                        break;

                    case STOPPED:
                        stopDownloadButton.setEnabled(false);
                        startDownloadButton.setEnabled(true);
                        break;

                }


            } else {
                System.err.println("GUI: P2pView: downloadsTableRowSelected():" +
                        " type of ceil value is wrong (" + obj + ")");
                stopDownloadButton.setEnabled(false);
                startDownloadButton.setEnabled(false);
            }

            stopDownloadButton.validate();
            startDownloadButton.validate();

            obj = downloadsTable.getValueAt(i, 0);
            if (obj instanceof Integer) {
                int pos = ((Integer) obj).intValue();
                if (pos == downloadsTable.getRowCount()) {
                    bottom = true;
                }
                if (pos == 1) {
                    top = true;
                }

                moveBottomButton.setEnabled(!bottom);
                moveDownButton.setEnabled(!bottom);
                moveTopButton.setEnabled(!top);
                moveUpButton.setEnabled(!top);
                deleteDownloadButton.setEnabled(true);
                moveBottomButton.validate();
                moveDownButton.validate();
                moveTopButton.validate();
                moveUpButton.validate();
            } else {
                System.err.println("GUI: P2pView: downloadsTableRowSelected():" +
                        " type of ceil value is wrong (" + obj + ")");

            }

        } else if (i == -2 || i == -1) {
            stopDownloadButton.setEnabled(false);
            startDownloadButton.setEnabled(false);
            moveBottomButton.setEnabled(false);
            moveDownButton.setEnabled(false);
            moveTopButton.setEnabled(false);
            moveUpButton.setEnabled(false);
            deleteDownloadButton.setEnabled(false);
            stopDownloadButton.validate();
            startDownloadButton.validate();
            moveBottomButton.validate();
            moveDownButton.validate();
            moveTopButton.validate();
            moveUpButton.validate();
        }
    }//GEN-LAST:event_downloadsTableRowSelected

    private void sharedFilesTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sharedFilesTableMouseClicked
        // TODO add your handling code here:
        int id = sharedFilesTable.getSelectedColumn();
        if (id != -1) {
            removesharedButton.setEnabled(true);
        } else {
            removesharedButton.setEnabled(false);
        }

        removesharedButton.validate();
    }//GEN-LAST:event_sharedFilesTableMouseClicked

    private void startDownloadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startDownloadButtonActionPerformed
        // TODO add your handling code here:
        int selRow = downloadsTable.getSelectedRow();

        if (selRow != -1) {
            Integer id = (Integer) downloadsTable.getValueAt(selRow, DownloadTask.getPosId());
            manager.outStartDownload(id - 1);
        } else {
            System.err.println("GUI: startDownloadButtonActionPerformed(): nothing" +
                    "selected");
        }
    }//GEN-LAST:event_startDownloadButtonActionPerformed

    private void stopDownloadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopDownloadButtonActionPerformed
        // TODO add your handling code here:
        int selRow = downloadsTable.getSelectedRow();
        if (selRow != -1) {
            Integer id = (Integer) downloadsTable.getValueAt(selRow, DownloadTask.getPosId());
            manager.outStopDownload(id - 1);
        } else {
            System.err.println("GUI: stopDownloadButtonActionPerformed(): nothing" +
                    "selected");
        }
    }//GEN-LAST:event_stopDownloadButtonActionPerformed

    private void moveTopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveTopButtonActionPerformed
        // TODO add your handling code here:
        int selRow = downloadsTable.getSelectedRow();
        if (selRow != -1) {
            Integer id = (Integer) downloadsTable.getValueAt(selRow, DownloadTask.getPosId());
            manager.outMoveTop(id - 1);
        } else {
            System.err.println("GUI: moveTopButtonActionPerformed(): nothing" +
                    "selected");
        }
    }//GEN-LAST:event_moveTopButtonActionPerformed

    private void moveUpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveUpButtonActionPerformed
        // TODO add your handling code here:
        int selRow = downloadsTable.getSelectedRow();
        if (selRow != -1) {
            Integer id = (Integer) downloadsTable.getValueAt(selRow, DownloadTask.getPosId());
            manager.outMoveUp(id - 1);
        } else {
            System.err.println("GUI: moveTopButtonActionPerformed(): nothing" +
                    "selected");
        }
    }//GEN-LAST:event_moveUpButtonActionPerformed

    private void moveDownButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveDownButtonActionPerformed
        // TODO add your handling code here:
        int selRow = downloadsTable.getSelectedRow();
        if (selRow != -1) {
            Integer id = (Integer) downloadsTable.getValueAt(selRow, DownloadTask.getPosId());
            manager.outMoveDown(id - 1);
        } else {
            System.err.println("GUI: moveTopButtonActionPerformed(): nothing" +
                    "selected");
        }
    }//GEN-LAST:event_moveDownButtonActionPerformed

    private void moveBottomButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveBottomButtonActionPerformed
        // TODO add your handling code here:
        int selRow = downloadsTable.getSelectedRow();
        if (selRow != -1) {
            Integer id = (Integer) downloadsTable.getValueAt(selRow, DownloadTask.getPosId());
            manager.outMoveBottom(id - 1);
        } else {
            System.err.println("GUI: moveTopButtonActionPerformed(): nothing" +
                    "selected");
        }
    }//GEN-LAST:event_moveBottomButtonActionPerformed

    private void deleteDownloadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteDownloadButtonActionPerformed
        // TODO add your handling code here:
        int selRow = downloadsTable.getSelectedRow();
        if (selRow != -1) {
            Integer id = (Integer) downloadsTable.getValueAt(selRow, DownloadTask.getPosId());
            manager.outDelDownload(id);
        }
}//GEN-LAST:event_deleteDownloadButtonActionPerformed
    @Action
    public void quitRequest() {
        //TODO: send command to controller
        manager.outQuit();
    }

    private String getDownloadFilename(int id) {
        return (String) downloadsTable.getValueAt(id, DownloadTask.getFilenameId());
    }

    private String getSharedFilename(int id) {
        return (String) sharedFilesTable.getValueAt(id, SharedFile.getFilenameId());
    }

    private String getSharedPath(int id) {
        return (String) sharedFilesTable.getValueAt(id, SharedFile.getPathId());
    }

    @Action
    public void showActiveHostsReq() {
        activeHostsButton.setEnabled(false);
        manager.showActiveHostsReq();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton activeHostsButton;
    private javax.swing.JButton addSharedButton;
    private javax.swing.JButton deleteDownloadButton;
    private javax.swing.JTable downloadsTable;
    private javax.swing.JMenu editMenu;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JButton moveBottomButton;
    private javax.swing.JButton moveDownButton;
    private javax.swing.JButton moveTopButton;
    private javax.swing.JButton moveUpButton;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JMenuItem propertiesMenu;
    private javax.swing.JButton removesharedButton;
    private javax.swing.JTable sharedFilesTable;
    private javax.swing.JButton startDownloadButton;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JButton stopDownloadButton;
    private javax.swing.JPanel viewDownloads;
    private javax.swing.JTabbedPane viewPanels;
    private javax.swing.JPanel viewShared;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    private PropertiesWindow propertiesWin;
}
